//
//  OwnerViewController.m
//  FeiYang
//
//  Created by User on 15/10/12.
//  Copyright © 2015年 feiyang. All rights reserved.
//

#import "OwnerViewController.h"
#import "LoginViewController.h"
#import "ProblemFeedBackViewController.h"
#import "ChangePswViewController.h"
#import "MyInfoViewController.h"
#import "ProblemFeedBackViewController.h"
#import "OfflineViewController.h"
@interface OwnerViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
{
    NSIndexPath *index;
}
@property (nonatomic,retain)UITableView *myTableView;
@property (nonatomic,retain)UIButton *headBtn;//头像的按钮
@property (nonatomic,retain)UIView *bgView;
@property (nonatomic,retain)UIButton *loginBtn;
@property (nonatomic,retain)UIButton * exitBtn;
@property (nonatomic,retain)NSArray *firstGroupImgNameArr;
@property (nonatomic,retain)NSArray *firstTitleNameArr;
@property (strong, nonatomic)UIView *backColorView;
@property (strong, nonatomic)UIView *logoView;

@end

@implementation OwnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"我的"];
    [self.view addSubview:topView];
    
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    [self layoutTableview];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([AccountTools isLogin]==NO) {
        
        [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        self.loginBtn.frame = CGRectMake(X(self.headBtn)-60.0f, NH(self.headBtn) + 20.0f, width(self.headBtn)+120.0f, 44.0f);
        [self.loginBtn setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
        self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
        self.loginBtn.layer.borderWidth = 1.0f;
        self.loginBtn.layer.borderColor = [[UIColor hexStringToColor:@"#FFFFFF"]CGColor];
        self.loginBtn.layer.cornerRadius = 2;
        self.loginBtn.enabled = YES;
        self.exitBtn.hidden = YES;
        self.logoView.hidden = NO;
        self.headBtn.enabled = NO;
        
    }else{
        
        [self.headBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Index_Url_Test,[[NSUserDefaults standardUserDefaults]objectForKey:@"userHeadPhoto"]]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_default_head"]];
        [self.loginBtn setTitle:[[NSUserDefaults standardUserDefaults]objectForKey:@"jobNumber"] forState:UIControlStateNormal];
        [self.loginBtn setTitleColor:[UIColor hexStringToColor:@"#FFFFFF"] forState:UIControlStateNormal];
        self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:28.0f];
        self.loginBtn.layer.borderColor = [[UIColor clearColor]CGColor];
        self.exitBtn.hidden = NO;
        self.exitBtn.alpha = 1;
        self.logoView.hidden = YES;
        self.loginBtn.enabled = NO;
        self.headBtn.enabled = YES;
    }
    
    [self.myTableView reloadData];
    
    
    
}
- (void)layoutTableview
{
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0 ,64.0f,SCREEN_WIDTH ,SCREEN_HEIGHT-64.0f-49.0f) style:UITableViewStyleGrouped];
    self.myTableView.backgroundColor = [UIColor clearColor];
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.bounces = TRUE;
    [self.view addSubview:self.myTableView];
    
    
    
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , 9*SCREEN_WIDTH/16) ];
    self.bgView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    
    
    self.headBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.headBtn setBackgroundImage:[UIImage imageNamed:@"img_default_head"] forState:UIControlStateNormal];
    self.headBtn.frame = CGRectMake((SCREEN_WIDTH-80.0f)/2, 32.0f, 80.0f, 80.0f);
    self.headBtn.layer.cornerRadius =self.headBtn.bounds.size.width/2.0;
    self.headBtn.layer.masksToBounds = YES;
    [self.headBtn addTarget:self action:@selector(headBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:self.headBtn];
    
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginBtn.frame = CGRectMake(X(self.headBtn)-60.0f, NH(self.headBtn) + 20.0f, width(self.headBtn)+120.0f, 20.0f);
    [self.loginBtn addTarget:self action:@selector(loginBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.bgView addSubview:self.loginBtn];
    
    
    self.myTableView.tableHeaderView = self.bgView;
    
    
    UIView * footerView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80.0f)];
    
    
    //安全退出
    self.exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(16.0f,16.0f, SCREEN_WIDTH-32.0f, 44.0f)];
    [self.exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [self.exitBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.exitBtn.layer.cornerRadius =  2.0;
    self.exitBtn.layer.masksToBounds = YES;
    self.exitBtn.layer.borderWidth = 1;
    self.exitBtn.layer.borderColor = [[UIColor hexStringToColor:COLOR_VALUE] CGColor];
    [self.exitBtn setTitleColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
    [self.exitBtn addTarget:self action:@selector(exitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.exitBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17.0f];
    [footerView addSubview:self.exitBtn];
    
    
    self.logoView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-90.0f)/2, 0.0f, 90.0f, 70.0f)];
    [footerView addSubview:self.logoView];
    
    UIImageView *logoImgView = [[UIImageView alloc]initWithFrame:CGRectMake((90.0f-44.0f)/2,10.0f, 44.0f, 44.0f)];
    logoImgView.image = [UIImage imageNamed:@"my_logo"];
    [self.logoView addSubview: logoImgView];
    
    UILabel *versionLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, NH(logoImgView)+20.f, width(self.logoView), 80.0f-height(logoImgView)-44.0f-10.f)];
    versionLabel.text = [NSString stringWithFormat:@"菲阳影视 V%@",[AccountTools getLocalVersion]] ;
    versionLabel.font = [UIFont systemFontOfSize:12.0f];
    versionLabel.textColor = [UIColor hexStringToColor:@"#bdbdbd"];
    versionLabel.textAlignment = NSTextAlignmentCenter;
    [self.logoView addSubview:versionLabel];
    
    
    self.myTableView.tableFooterView = footerView;
    self.firstGroupImgNameArr = [NSArray arrayWithObjects:@"my_icon1",@"my_icon2",@"my_icon3",@"my_icon4",@"my_icon5", nil];
    self.firstTitleNameArr = [NSArray arrayWithObjects:@"我的活动",@"个人资料",@"重置密码",@"问题反馈",@"联系我们", nil];
    
    
}

#pragma mark -  tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else{
        return 4;
    }
    
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 43.0f, SCREEN_WIDTH ,0.5f)];
        separtor.backgroundColor = [UIColor hexStringToColor:@"#e5e5e5"];
        [cell addSubview:separtor];//分割线
        
        
        
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.frame = CGRectMake(26.0f , 10.0f ,24.0f ,24.0f );
        imageView.tag = 1;
        [cell.contentView addSubview:imageView];
        
        UILabel *mainLabel = [[UILabel alloc]init];
        mainLabel.tag = 2;
        mainLabel.frame = CGRectMake(NW(imageView)+10.0f,7.0f ,100.0f,30.0f );
        mainLabel.font = [UIFont systemFontOfSize:14.0f];
        [cell.contentView addSubview:mainLabel];
        
        
        if (indexPath.section==1) {
            UILabel *detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(NW(imageView)+110.0f, 7.0f, SCREEN_WIDTH-NW(imageView)-10.0f-110.0f, 30.0f)];
            detailLabel.font = [UIFont systemFontOfSize:14.0f];
            detailLabel.tag = 3;
            detailLabel.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:detailLabel];
            
            if (indexPath.row==3) {
                index = indexPath;
            }
            
            
        }
        
        
    }
    
    
    UIImageView *imgView = (UIImageView*)[cell.contentView viewWithTag:1];
    UILabel *mainLabel = (UILabel*)[cell.contentView viewWithTag:2];
    UILabel *detailLabel = (UILabel*)[cell.contentView viewWithTag:3];
    if (indexPath.section==0) {
        
        if (indexPath.row==0) {
            mainLabel.text = [self.firstTitleNameArr objectAtIndex:0];
            imgView.image =[UIImage imageNamed:[self.firstGroupImgNameArr objectAtIndex:0]] ;
        }
    }else{
        
        if (indexPath.row==0) {
            mainLabel.text = [self.firstTitleNameArr objectAtIndex:1];
            imgView.image =[UIImage imageNamed:[self.firstGroupImgNameArr objectAtIndex:1]] ;
        }else if (indexPath.row==1){
            mainLabel.text = [self.firstTitleNameArr objectAtIndex:2];
            imgView.image =[UIImage imageNamed:[self.firstGroupImgNameArr objectAtIndex:2]] ;

        }else if (indexPath.row==2){
            mainLabel.text = [self.firstTitleNameArr objectAtIndex:3];
            imgView.image =[UIImage imageNamed:[self.firstGroupImgNameArr objectAtIndex:3]] ;
        }else{
            
            mainLabel.text = [self.firstTitleNameArr objectAtIndex:4];
            imgView.image =[UIImage imageNamed:[self.firstGroupImgNameArr objectAtIndex:4]] ;
            detailLabel.text = @"021-30168888";
        }
        
    }
    
    return cell;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * backView = [[UIView alloc]init];
    backView.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    return backView;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    return 8.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * backview = [[UIView alloc]init];
    backview.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    return backview;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==0) {
        //我的活动
        
//        if ([AccountTools isLogin]==NO) {
//            
//            LoginViewController *loginVC = [[LoginViewController alloc]init];
//            loginVC.backBtHide = TRUE;
//            [self presentViewController:loginVC animated:YES completion:^(void){}];
//            
//        }else{

        OfflineViewController *offlineVC = [[OfflineViewController alloc]init];
        [self.navigationController pushViewController:offlineVC animated:YES];
            
//        }
        
    }else if (indexPath.section==1){
        
        if (indexPath.row==0) {
            //个人资料
//            
//            if ([AccountTools isLogin]==NO) {
//                
//                LoginViewController *loginVC = [[LoginViewController alloc]init];
//                loginVC.backBtHide = TRUE;
//                [self presentViewController:loginVC animated:YES completion:^(void){}];
//                
//            }else{
            
                MyInfoViewController  *myInfoVC = [[MyInfoViewController alloc]init];
                [self.navigationController pushViewController:myInfoVC animated:YES];
//            }

            
            
        }else if (indexPath.row==1){
            //重置密码
            if ([AccountTools isLogin]==NO) {
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                loginVC.backBtHide = TRUE;
                [self presentViewController:loginVC animated:YES completion:^(void){}];
                
            }else{
                
                ChangePswViewController *changePswVC = [[ChangePswViewController alloc]init];
                [self.navigationController pushViewController:changePswVC animated:YES];
            }

            
        }else if (indexPath.row==2){
            //问题反馈
            
            ProblemFeedBackViewController *problemFeedBackVC = [[ProblemFeedBackViewController alloc]init];
            [self.navigationController pushViewController:problemFeedBackVC animated:YES];
        
        }else{
            //联系我们
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"是否想要呼叫电话021-30168888?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"呼叫", nil];
            [alert show];
        }
    
    }
    

}

#pragma mark -  actionSheet
- (void)headBtnAction
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        
        //相册
        [self showTheImagePickerController:1];
        
        
    }else if(buttonIndex == 1){
        //拍照
        [self showTheImagePickerController:2];
        
    }else{
        //取消
    }
    
    
}

#pragma mark - 安全退出按钮
- (void)exitBtnClick:(UIButton*)btn
{
    
    [AccountTools exitLogin];
    btn.hidden = YES;
    [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
    [self.headBtn setBackgroundImage:[UIImage imageNamed:@"img_default_head"] forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.loginBtn.layer.borderColor = [[UIColor hexStringToColor:@"#FFFFFF"]CGColor];
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    self.loginBtn.layer.borderWidth = 1.0f;
    self.loginBtn.frame = CGRectMake(X(self.headBtn)-60.0f, NH(self.headBtn) + 20.0f, width(self.headBtn)+120.0f, 44.0f);
    [self.loginBtn setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
    self.loginBtn.enabled = YES;
    self.headBtn.enabled = NO;
    self.logoView.hidden = NO;
    
}

#pragma mark -  拍照或相册选取  0相册 1拍照
- (void)showTheImagePickerController:(int)carmerType{
    
    NSInteger sourceType;
    if (carmerType ==1) {
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }else if(carmerType == 2){
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    imgPicker.delegate = self;
    imgPicker.allowsEditing = YES;
    imgPicker.sourceType = sourceType;
    [imgPicker.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil]];
    [self presentViewController:imgPicker animated:YES completion:^{
        // 改变状态栏的颜色  为正常  这是这个独有的地方需要处理的
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
    [[AnimationIndicator sharedIndicator] startAnimation];
    //上传头像
//    NSString * dataStr = [AppGlobalClass PostImagesToServer:UPDATEUSERHEADPHOTO dicPostParams:(NSMutableDictionary*)@{@"token":[AccountTools getUserToken]} dicImages:(NSMutableDictionary*)@{@"HeadPhoto":image}];
//    NSDictionary *dictionary = [AppGlobalClass dictionaryWithJsonString:dataStr];
//    
//    if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
//    {
//        [[NSUserDefaults standardUserDefaults]setObject:[[[[[dictionary objectForKey:@"responseData"] firstObject]objectForKey:@"rows"] firstObject] objectForKey:@"userHeadPhoto"] forKey:@"userHeadPhoto"];
//        ALERT_VIEW(@"上传成功");
//        
//        [self.headBtn setBackgroundImage:image forState:UIControlStateNormal];
//        
//        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
//        
//    }
//    else{
//        if ([[dictionary objectForKey:@"message"] isEqualToString:@"登录失败，请重新登录"])
//        {
//            
//        }else
//        {
//            if ([CheckNetWork isExistenceNetwork]==FALSE) {
//                ALERT_VIEW(@"请检查网络");
//                
//            }
//            else{
//                ALERT_VIEW([dictionary objectForKey:@"message"]);
//                
//            }
//        }
//        
//        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
//    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==200) {
        if (buttonIndex==1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://021-30168888"]];
        }
    }else{
        
        if (buttonIndex==1) {
            //清除缓存
            [[SDImageCache sharedImageCache] clearDisk];//清除图片缓存
            
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                               
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               
                           });//清除其他缓存文件
            
            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:index];
            UILabel *detailLabel = (UILabel*)[cell.contentView viewWithTag:3];
            detailLabel.text = @"0.00M";
            
            [self.myTableView reloadData];
            
            
            
        }
    }
}

- (void)loginBtnAction:(id)sender
{
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    loginVC.backBtHide = TRUE;
    [self presentViewController:loginVC animated:TRUE completion:^(void){}];
}

@end
